import axios from 'axios'
import store from '@/store'
import router from '@/router'
import QS from 'qs'
import {Message} from 'view-design'

const service = axios.create({
    baseURL: "",
    // baseURL: '',
    timeout: 100000 // request timeout
})

// 响应拦截
service.interceptors.request.use(
    async config => {
        if (config.type !== 'json') {
            config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
        } else {
            config.headers['Content-Type'] = 'application/json;charset=UTF-8'
        }
        if (config.method === 'post') {
            if (config.type === 'upload') {
                config.headers['Content-Type'] = 'application/multipart/form-data'
            } else {
                if (config.type !== 'json') {
                    config.data = QS.stringify({
                        ...config.data
                    })
                } else if (config.isBlob) {
                    config.responseType = 'arraybuffer'
                }
            }
        }

        // do something before request is sent
        if (store.getters.access_token) {
            config.headers['Authorization'] = 'Bearer ' + store.getters.access_token
        } else {
            config.headers['Authorization'] = 'Basic d2ViOnh4'
        }
        config.headers['user_id'] = store.getters.userId
        config.headers['client_id'] = 'web'
        config.headers['device_id'] = store.getters.deviceId

        let expiresDate = sessionStorage.getItem('expires_in')

        // expiresDate = Number(expiresDate)
        if (expiresDate != null && expiresDate <= new Date().getTime() / 1000) {

            await store.dispatch('app/refreshLogin')
            config.headers['Authorization'] = 'Bearer ' + store.getters.access_token

        }


        // if(store.getters.expires_in != ''){
        //  console.log(store.getters.expires_in)

        // }
        // console.log(store.getters.expires_in);
        // 将请求类型改为普通的表单类型

        return config
    },
    error => {
        // do something with request error
        return Promise.reject(error)
    }
)
service.interceptors.response.use(
    response => {
        if (response.status != 200) {
            Message.error({
                background: true,
                content: response.data.Message
            });
        }
        return response
    },
    error => {
        if (error.response.status == 422) {
            sessionStorage.clear()
            store.dispatch('app/resetToken')
            Message.destroy()
            router.push('/')
            return
        }
        Message.error({
            background: true,
            content: error
        });
        return Promise.reject(error)
    }
)

export default service
